package cn.zurish.cloud.security.service;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;

@Component
public class TokenValidationService {

    public boolean validateToken(PersistentRememberMeToken token, String presentedToken) {
        return BCrypt.checkpw(presentedToken, token.getTokenValue());
    }


    JdbcTemplate jdbcTemplate;

    @Scheduled(fixedRate = 24 * 60 * 60 * 1000) // 每日清理
    public void purgeExpiredTokens() {
        jdbcTemplate.update(
                "DELETE FROM persistent_logins WHERE last_used < ?",
                Date.from(Instant.now().minus(60, ChronoUnit.DAYS))
        );
    }

}
